package cn.iocoder.yudao.im.service.Impl;

import cn.iocoder.yudao.im.domain.NoticeImTask;
import cn.iocoder.yudao.im.mapper.NoticeImTaskMapper;
import cn.iocoder.yudao.im.service.NoticeImTaskService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 群聊任务表 服务实现类
 * </p>
 *
 * @author ZCC
 * @since 2024-07-02
 */
@Service
public class NoticeImTaskServiceImpl extends ServiceImpl<NoticeImTaskMapper, NoticeImTask> implements NoticeImTaskService {

    @Resource
    private AdminUserService userService;


    @Override
    public NoticeImTask getTaskById(Long taskId) {
        NoticeImTask task = this.getById(taskId);
        getTask(task);
        task.setCreateUserName(userService.getUser(Long.parseLong(task.getCreateUser())).getUsername());
        task.setLiablePersonName(userService.getUser(Long.parseLong(task.getLiablePerson())).getUsername());
        return task;
    }

    @Override
    @Transactional
    public NoticeImTask saveTask(NoticeImTask task) {
        this.save(task);
        return task;
    }

    @Override
    public List<NoticeImTask> taskList(NoticeImTask task) {
        List<NoticeImTask> noticeImTasks = this.baseMapper.taskList(task);
        for (NoticeImTask noticeImTask : noticeImTasks) {
            getTask(noticeImTask);
        }

        return noticeImTasks;

    }

    private void getTask(NoticeImTask task) {
        List<AdminUserDO> executorList = new ArrayList<>();
        List<AdminUserDO> participantsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(task.getExecutor())) {
            String executor = task.getExecutor();
            String[] executorIds = executor.split(",");
            for (String executorId : executorIds) {
                executorList.add(userService.getUser(Long.parseLong(executorId)));
            }
        }
        if (StringUtils.isNotEmpty(task.getParticipants())) {
            String participants = task.getParticipants();
            String[] participantsIds = participants.split(",");
            for (String participantsId : participantsIds) {
                participantsList.add(userService.getUser(Long.parseLong(participantsId)));
            }
        }
        task.setExecutorList(executorList);
        task.setParticipantsList(participantsList);
    }
}
